package com.itheima.sfbx.file.test;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PartETag;
import com.aliyun.oss.model.UploadPartRequest;
import com.aliyun.oss.model.UploadPartResult;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@RequiredArgsConstructor
public class MyThread extends Thread{

    final int i;
    final long partSize;
    final int partCount;
    final long fileLength;
    final String bucketName;
    final String objectName;
    final String uploadId;
    final File sampleFile;
    final OSS ossClient;
    final List<PartETag> partETags;
    final CountDownLatch latch;

    @SneakyThrows
    @Override
    public void run() {
        System.out.println("开始分片上传第"+i+"片");
        long startPos = i * partSize;
        long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
        UploadPartRequest uploadPartRequest = new UploadPartRequest();
        uploadPartRequest.setBucketName(bucketName);
        uploadPartRequest.setKey(objectName);
        uploadPartRequest.setUploadId(uploadId);
        // 设置上传的分片流。
        // 以本地文件为例说明如何创建FIleInputstream，并通过InputStream.skip()方法跳过指定数据。
        InputStream instream = new FileInputStream(sampleFile);
        instream.skip(startPos);
        uploadPartRequest.setInputStream(instream);
        // 设置分片大小。除了最后一个分片没有大小限制，其他的分片最小为100 KB。
        uploadPartRequest.setPartSize(curPartSize);
        // 设置分片号。每一个上传的分片都有一个分片号，取值范围是1~10000，如果超出此范围，OSS将返回InvalidArgument错误码。
        uploadPartRequest.setPartNumber( i + 1);
        // 每个分片不需要按顺序上传，甚至可以在不同客户端上传，OSS会按照分片号排序组成完整的文件。
        UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
        // 每次上传分片之后，OSS的返回结果包含PartETag。PartETag将被保存在partETags中。
        partETags.add(uploadPartResult.getPartETag());
        latch.countDown();//表示执行完毕，把闭锁-1
        System.out.println("第"+i+"个分片执行完毕");
    }
}
